// permissionManager.js

export default {
  isApp: typeof plus !== 'undefined',
  plusReadyTriggered: false,

  // 初始化
  init() {
    if (this.isApp) {
      document?.addEventListener('plusready', () => {
        this.plusReadyTriggered = true;
        console.log('plusReady 事件触发');
      });
    }
  },

  // 请求权限
  async requestPermission(permission, description) {
    if (!this.isApp) return true; // H5 环境无需处理权限

    if (this.plusReadyTriggered) {
      return await this.checkAndRequestPermission(permission, description);
    } else {
      return new Promise((resolve) => {
        document?.addEventListener('plusready', async () => {
          this.plusReadyTriggered = true;
          resolve(await this.checkAndRequestPermission(permission, description));
        }, {
          once: true
        });
      });
    }
  },

  // 检查和请求权限
  async checkAndRequestPermission(permission, description) {
    const main = plus.android.runtimeMainActivity();
    const ContextCompat = plus.android.importClass('androidx.core.content.ContextCompat');
    const ActivityCompat = plus.android.importClass('androidx.core.app.ActivityCompat');
    const PackageManager = plus.android.importClass('android.content.pm.PackageManager');

    return new Promise((resolve) => {
      const hasPermission = ContextCompat.checkSelfPermission(main, permission) === PackageManager
        .PERMISSION_GRANTED;
      if (hasPermission) {
        resolve(true);
      } else {
        uni.showModal({
          title: '权限申请',
          content: description,
          success: (res) => {
            if (res.confirm) {
              ActivityCompat.requestPermissions(main, [permission], 0);
              // 权限申请结果回调
              document?.addEventListener('onRequestPermissionsResult', (event) => {
                const requestResults = event.detail.requestResults;
                resolve(requestResults[permission] === PackageManager.PERMISSION_GRANTED);
              });
            } else {
              resolve(false);
            }
          }
        });
      }
    });
  }
};